//
//  StoreAddViewController.swift
//  Reader
//
//  Created by home on 2019/10/15.
//  Copyright © 2019 codeguesser. All rights reserved.
//

import UIKit

class StoreAddViewController: UIViewController {
    var index = 0
    var addAction:(Int,String,String)->Void = {_,_,_  in}
    @IBOutlet weak var indexLabel: UILabel!
    @IBOutlet weak var linkField: UITextField!
    @IBOutlet weak var bookNameField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.indexLabel.text = "\(index)"
        self.title = "手动添加书"
    }

    @IBAction func search(_ sender: Any) {
        guard (bookNameField.text ?? "").isNotEmpty else {
            UIAlertController.alertMessage("请输入书名")
            bookNameField.becomeFirstResponder()
            return
        }
        hideAllKeyboard()
        let vc = WebViewController2(nibName: WebViewController2.identifier)
        vc.title = "搜索\(bookNameField.text ?? "")"
        vc.url = URL(string: "https://www.baidu.com/s?wd=\(bookNameField.text ?? "")".toUrlEncodeString() ?? "")
        vc.saveAction = {[weak self] urlString in
            if let SSelf = self{
                SSelf.linkField.text = urlString
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func add(_ sender: Any) {
        guard (bookNameField.text ?? "").isNotEmpty else {
            UIAlertController.alertMessage("请输入书名")
            bookNameField.becomeFirstResponder()
            return
        }
        guard (linkField.text ?? "").isNotEmpty else {
            UIAlertController.alertMessage("请输入有效的目录链接")
            linkField.becomeFirstResponder()
            return
        }
        hideAllKeyboard()
        self.addAction(index,bookNameField.text ?? "",linkField.text ?? "")
        self.navigationController?.popVC()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        hideAllKeyboard()
    }
    func hideAllKeyboard() {
        bookNameField.resignFirstResponder()
        linkField.resignFirstResponder()
    }
}
